<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { deleteNewsApi, getNewsApi } from "@/api/news"
import { type GetNewsData } from "@/api/news/types/index"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import NewsTypeSelect from "./components/newsTypeSelect.vue"
import { TYPE_MAP } from "./enums"
import { useRouter } from "vue-router"
import { getBasePath } from "@/api/common/index"
import { onMounted } from "vue"
const router = useRouter()
defineOptions({
  // 命名当前组件
  name: "News"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 删
const handleDelete = (row: GetNewsData) => {
  ElMessageBox.confirm(`正在删除：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteNewsApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: GetNewsData) => {
  router.push(`/news/operate/${row.id}`)
}
//#endregion

//#region 查
const tableData = ref<GetNewsData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  title: "",
  type: ""
})
const getTableData = () => {
  loading.value = true
  getNewsApi({
    page: paginationData.page,
    size: paginationData.size,
    title: searchData.title,
    type: searchData.type
  })
    .then(({ data }) => {
      paginationData.total = data.total
      tableData.value = data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.page === 1 ? getTableData() : (paginationData.page = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.page, () => paginationData.size], getTableData, { immediate: true })
const basePath = ref<string>("")
const imgUrl = ref<string>("")
const dialogVisible = ref<boolean>(false)
const dialogImgVisible = ref<boolean>(false)
const content = ref<string>("")
const handleImgPreview = (value: string) => {
  imgUrl.value = value
  dialogImgVisible.value = true
}
const handlePreview = (value: string) => {
  content.value = value
  dialogVisible.value = true
}
onMounted(async () => {
  const { data } = await getBasePath()
  basePath.value = data
})
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="title" label="新闻标题">
          <el-input v-model="searchData.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="type" label="新闻类型">
          <news-type-select v-model="searchData.type" placeholder="请选择" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="router.push(`/news/operate`)">新增新闻</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="type" label="新闻类型" align="center">
            <template #default="scope">
              {{ TYPE_MAP[scope.row.type] }}
            </template>
          </el-table-column>
          <el-table-column prop="author" label="作者" />
          <el-table-column prop="cover_url" label="新闻封面" align="center">
            <template #default="scope">
              <img
                :src="basePath + scope.row.cover_url"
                style="height: 40px"
                @click="() => handleImgPreview(basePath + scope.row.cover_url)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="tags" label="新闻标签" />
          <el-table-column prop="source" label="新闻来源" />
          <el-table-column prop="isRecommend" label="新闻是否推荐">
            <template #default="scope">
              {{ scope.row.isRecommend === "1" ? "推荐" : "常规" }}
            </template>
          </el-table-column>
          <el-table-column prop="abstract" label="新闻摘要" />
          <el-table-column prop="content" label="文章内容">
            <template #default="scope">
              <el-button type="primary" @click="() => handlePreview(scope.row.content)">预览</el-button>
            </template>
          </el-table-column>

          <el-table-column prop="publish_date" label="发布时间" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.size"
          :currentPage="paginationData.page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog v-model="dialogVisible" title="新闻内容预览" width="800" align-center>
      <div v-html="content" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogImgVisible" title="图片预览" width="800" align-center>
      <img :src="imgUrl" style="width: 700px" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogImgVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
